package com.example.userdome.Interceptor;

import com.example.userdome.pojo.User;
import com.example.userdome.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {
   @Resource
    private IUserService iUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Integer userId=(Integer) request.getSession().getAttribute("id");//获取当前用户id
        if (userId==null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //获取请求中的用户id
        Integer studentId=Integer.parseInt(request.getParameter("id"));
        //查询用户id
        User user=iUserService.getById(studentId);
        if (user==null){
            //用户不存在
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        if (!user.getId().equals(userId)){
            //用户信息无法对应
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        return true;
    }
}
